package com.yjr.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.yjr.common.constant.AuthServerConstant;
import com.yjr.common.exception.BizCodeEnum;
import com.yjr.common.utils.R;
import com.yjr.common.vo.MemberRsepVo;
import com.yjr.gulimall.auth.feign.MemberFeignService;
import com.yjr.gulimall.auth.feign.ThirdPartFeignService;
import com.yjr.gulimall.auth.vo.UserLoginVo;
import com.yjr.gulimall.auth.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class LoginController {

//    @GetMapping("/login.html")
//    public  String loginPage(){
//        return "login";
//    }
//
//    @GetMapping("/reg.html")
//    public  String regPage(){
//        return "reg";
//    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        //接口防刷
        //先判断redis缓存中是否存在该手机号的验证码
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotBlank(s)) {
            //如果redis中存在数据，判断数据是否已经存在了60秒，防止刷新页面再次在60秒内发送验证码
            Long CuuTime = Long.parseLong(s.split("_")[1]);
            if (System.currentTimeMillis() - CuuTime < 60 * 1000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
            String code = UUID.randomUUID().toString().substring(0,5);
            String redisCode=code+"_"+System.currentTimeMillis();
            stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,redisCode,5, TimeUnit.MINUTES);
            //调用远程服务发送验证码
            try {
               return thirdPartFeignService.sendCode(phone,code);
            } catch (Exception e) {
                log.warn("远程调用不知名错误 [无需解决]");
            }

       return  R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){

        if(result.hasErrors()){

            // 将错误属性与错误信息一一封装
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, fieldError -> fieldError.getDefaultMessage()));
            // addFlashAttribute 这个数据只取一次
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //获取验证码
        String code = vo.getCode();
            //比对验证码
            String redisCode= stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
            if(StringUtils.isNotEmpty(redisCode)){
                if(code.equals(redisCode.split("_")[0])){
                    //删除验证码
                    stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                    // 调用远程服务进行注册
                    R r = memberFeignService.register(vo);
                    if(r.getCode() == 0){
                        // 成功
                        return "redirect:http://auth.gulimall.com/login.html";
                    }else{
                        Map<String, String> errors = new HashMap<>();
                        errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                        redirectAttributes.addFlashAttribute("errors",errors);
                        return "redirect:http://auth.gulimall.com/reg.html";
                    }
                }else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("code", "验证码错误");
                    // addFlashAttribute 这个数据只取一次
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            }
            else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                // addFlashAttribute 这个数据只取一次
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
    }


    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session){
        // 远程登录
        R r = memberFeignService.login(userLoginVo);
        if(r.getCode() == 0){
            // 登录成功
            MemberRsepVo rsepVo = r.getData("data", new TypeReference<MemberRsepVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER, rsepVo);
            log.info("\n欢迎 [" + rsepVo.getUsername() + "] 登录");
            return "redirect:http://gulimall.com";
        }else {
            HashMap<String, String> error = new HashMap<>();
            // 获取错误信息
            error.put("msg", r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", error);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
